#
#===============================================================================
#
#         FILE:  NetStat.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  FreeBSD calculations currently just do some simple math based
#        	on netstat statistics, and likely are not as accurate as numbers
#        	gotten from /proc/net/dev on linux.
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/20/2010 06:06:11 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::NetStat;

use POSIX;

my @uname = uname;
my $UNAME = $uname[0];
undef @uname;
if( $UNAME eq 'Linux' ) {
    eval "use Sys::Statistics::Linux::NetStats";
} else { 
    # I hope it's freebsd or compatible netstat, because that's what I'm assuming
}

sub register {
    my $self = shift;

    return ('cmd' => 'netstat', 'pat' => '^!netstat');
}

sub help {
    my $self = shift;
    
    return ('Network Statistics');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    if( ! $conf{'net_interface'} ) {
	if( $UNAME eq 'Linux' ) {
	    $conf{'net_interface'} = 'eth0';
	}
	else {
	    $conf{'net_interface'} = `netstat -i | awk '/Link/ {print \$1}' | head -1`;
	}
    }

    my %data;

    if( $UNAME eq 'Linux' ) {
	my $lnx = Sys::Statistics::Linux::NetStats->new;
	$lnx->init;
	sleep 1;
	%data = %{${$lnx->get}{$conf{'net_interface'}}};
    }
    else {
	if( ! `which netstat` ) {
	    warn "unable to find netstat";
	    return;
	}

	my $netstat = `netstat -I $conf{'net_interface'} -bd | grep Link`;
	$netstat =~ /([^ ]+)\s+([\d]+)\s+([^ ]+)\s+([^ ]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)/;
	my ($int, $mtu, $net, $addr, $ipkts, $ierrs, $ibytes, $opkts, $oerrs, $obytes, $coll, $drop) =
	    ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12);
	sleep 2;
	my $netstat2 = `netstat -I $conf{'net_interface'} -bd | grep Link`;
	$netstat2 =~ /([^ ]+)\s+([\d]+)\s+([^ ]+)\s+([^ ]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)/;
	my ($int2, $mtu2, $net2, $addr2, $ipkts2, $ierrs2, $ibytes2, $opkts2, $oerrs2, $obytes2, $coll2, $drop2) =
	    ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12);

	%data = (
		'rxpcks' => ($ipkts2 - $ipkts)/2,
		'txpcks' => ($opkts2 - $opkts)/2,
		'rxbyt' => ($ibytes2 - $ibytes)/2,
		'txbyt' => ($obytes2 - $obytes)/2,
		);
    }

    $kernel->post($sender => privmsg => $target =>
	    sprintf('pps (in/out): %s/%s ; bps (in/out): %s/%s',
		$data{'rxpcks'}, $data{'txpcks'},
		$data{'rxbyt'}, $data{'txbyt'}));
}

1;
